package cn.tedu.boot51.controller;

import cn.tedu.boot51.entity.User;
import cn.tedu.boot51.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg( @RequestBody User user){
        System.out.println("user = " + user);
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            return 2;//代表用户名已存在
        }
        mapper.insert(user);//注册
        return 1;
    }

    //在参数列表里面声明session 即可得到当前客户端所对应的Session
    @RequestMapping("login")
    public int login(@RequestBody User user, HttpSession session){
        System.out.println("user = " + user);
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            if(user.getPassword().equals(u.getPassword())){
                //把当前登录的用户对象保存到会话当中
                //user代表用户输入的信息包括:用户名和密码
                //u代表从数据库中查询到的信息  包括: id ,用户名和密码,昵称
                session.setAttribute("user",u);

                return 1;//登录成功
            }
            return 3;//密码错误
        }
        return 2;//用户名不存在

    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        //从会话对象中得到登录成功时保存的用户对象
        User u = (User)session.getAttribute("user");
        return u;
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //把登录成功是保存的user对象删除
        session.removeAttribute("user");
    }
}
